//
//  TestViewController.m
//  KiklinkApp
//
//  Created by LJC on 14-9-19.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "TestViewController.h"
#import "UIView+loadWithNib.h"
#import "ChosenCell.h"
#import "MJRefresh.h"

#import "API.h"

static NSString *ChosenTableCellIdentifiers = @"ChosenCells";

@interface TestViewController ()
{
    NSMutableArray *tableArray;
    NSInteger page;
}
@end

@implementation TestViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
//    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:nil action:nil];
//    self.navigationItem.rightBarButtonItem = item;
    
    
    //leftNavItem
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    [searchBar setFrame:CGRectMake(0, 0, NavBarHeight*260/44, NavBarHeight*30/44)];
        searchBar.delegate = self;
    [searchBar setImage:[UIImage imageNamed:@"message.jpg"] forSearchBarIcon:UISearchBarIconResultsList state:UIControlStateNormal];
    UIBarButtonItem *leftNavBarItem = [[UIBarButtonItem alloc] initWithCustomView:searchBar];
    self.navigationItem.leftBarButtonItem = leftNavBarItem;
    
    
    //chosenTable
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.showsVerticalScrollIndicator = NO;
    [self.table registerClass:[UITableViewCell class] forCellReuseIdentifier:ChosenTableCellIdentifiers];
    [self setupRefresh];
    
    [self.table reloadData];
    
    tableArray = [[NSMutableArray alloc] init];
    page = 1;
    [self getData:page];
    page ++;
}

- (void)getData:(NSInteger)pageNum
{
    [API courseSearchWithKeyword:@"" distance:@0 tags:@"" category:@0 sortStyle:@"" pageNumber:[NSNumber numberWithInteger:pageNum] Callback:^(int stateCode, NSString *word, id content) {
        
        ProductPage *productPage = (ProductPage *)content;
        NSMutableArray *result = [[NSMutableArray alloc] initWithArray:productPage.result];
        
        [NSThread detachNewThreadSelector:@selector(loadData:) toTarget:self withObject:result];
        
    }];
}

- (void)loadData:(NSMutableArray *)result
{
    for (int i = 0; i < result.count; i ++) {
        ChosenCell *cell = [ChosenCell loadWithNib:@"ChosenCell" AndPostion:CGPointZero];
        [cell loadDataWithProduct:[result objectAtIndex:i]];
        [tableArray addObject:cell];
    }
    [self.table reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma tableView dataSource&delegate  &MJRefresh
- (void)setupRefresh
{
    [self.table addHeaderWithTarget:self action:@selector(headerRereshing)];
    //    [self.chosenTable headerBeginRefreshing];
    [self.table addFooterWithTarget:self action:@selector(footerRereshing)];
    
    self.table.headerPullToRefreshText = @"下拉可以刷新";
    self.table.headerReleaseToRefreshText = @"松开马上刷新";
    self.table.headerRefreshingText = @"正在刷新...";
    self.table.footerPullToRefreshText = @"上拉加载更多";
    self.table.footerReleaseToRefreshText = @"松开马上加载";
    self.table.footerRefreshingText = @"正在加载...";
}
- (void)headerRereshing
{
    page = 1;
    [tableArray removeAllObjects];
    [self getData:1];
    page = 2;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.table reloadData];
        [self.table headerEndRefreshing];
    });
}
- (void)footerRereshing
{
    [self getData:page];
    page ++;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.table reloadData];
        [self.table footerEndRefreshing];
    });
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tableArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ChosenCell *cell = [tableView dequeueReusableCellWithIdentifier:ChosenTableCellIdentifiers];
    
    if (cell == nil) {
        cell = [[ChosenCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ChosenTableCellIdentifiers];
    }
    cell = tableArray[indexPath.row];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 165;
}

#pragma tableView dataSource&delegate &MJRefresh End


#pragma mark - searchBar
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
// return NO to not become first responder  1
{
    searchBar.showsCancelButton = YES;
    return YES;
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
// called when text starts editing  2
{}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
// return NO to not resign first responder
{
    return YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
// called when text ends editing
{}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
// called when text changes (including clear)  4
{}

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text NS_AVAILABLE_IOS(3_0)
// called before text changes  3
{
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
// called when keyboard search button pressed  5
{}

- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar
// called when bookmark button pressed
{}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
// called when cancel button pressed
{
    searchBar.showsCancelButton = NO;
    [searchBar resignFirstResponder];
}

- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar NS_AVAILABLE_IOS(3_2)
// called when search results button pressed
{}

- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope NS_AVAILABLE_IOS(3_0)
{}

@end
